<template>
	<view class="index bf">
		<u-navbar class="nav" :title="title" leftIconColor="#fff" leftIconSize="24px" bgColor="#2F2F2F"
			titleStyle="color:#fff;font-size:30rpx;" :placeholder="true" safeAreaInsetTop :autoBack="true">
		</u-navbar>
		<view class="p10" style="background: #2F2F2F;">
			<!-- <view class="f-1" @click="toSearch">
				<u-input prefixIcon="search" placeholder="请输入商品名称" border="none" shape="circle"
					:customStyle="{height:'60rpx',paddingLeft:'20rpx',background:'#444444',color:'#999'}" :placeholderStyle="{color:'#999'}" v-model="searchValue" disabled>
				</u-input>
			</view> -->
			<view class="flex mt20 f-bt" v-if="form.diningType == 4">
				<view class="flex cf f14" @click="clickPeo">
					<view>{{form.type && form.type.name}}{{form.name}}</view>
					<view>（{{form.people}}人）</view>
					<u-icon name="edit-pen" color="#999" size="18"></u-icon>
				</view>
				<view class="cf f14" @click="moreShow = true">操作</view>
			</view>
		</view>

		<view class="main f-g-1 mt10">
			<scroll-view class="gleft" scroll-y scroll-with-animation :scroll-top="scrollTop">
				<view class="leftwrp">
					<view class="mi" @tap="handMenu(v.id,i)" v-for="(v, i) in categories" :key="i">
						<view class="sitem f-c-xc" :class="{active: ccId == v.id,'ysyj':i==sIndex+1,'yxyj':i==sIndex-1}"
							:style="{borderColor:ccId == v.id?'#fff':''}">
							<view class="f-c t-c f13">{{ v.name }}</view>
						</view>
					</view>
					<view class="mi" style="background: #F9F9FB;"></view>
					<view class="mi" style="background: #F9F9FB;"></view>
				</view>
			</scroll-view>
			<scroll-view class="gright" scroll-y scroll-with-animation :scroll-top="pstop" @scroll="psroll">
				<view class="wrp">
					<view class="glist" v-for="(v, i) in categories" :key="i" :id="`g-${v.id}`">
						<view class="gname flex">
							<!-- <view class="cn" :style="{background:subColor}">{{ v.name }}</view> -->
							<view class="nowei c9 flex f-y-c"><view class="cleal mr5"></view>{{ v.name }}</view>
						</view>
						<view class="gwrp">
							<view class="goods" v-for="(cv, ci) in v.goodsList" :key="ci">
								<view class="image mr10" v-if="goodSetData && goodSetData.productShow==2">
									<image :src="cv.logo" mode="aspectFill" class="image bs5"  @tap="handdl(cv)"></image>
									<view v-if='cv.goodsInventory<=0'
										class="p-a ysq f-c b0 cf w100 f12">已售罄</view>
								</view>
								<view class="content f-y-bt">
									<view class="name f-s wei">{{ cv.name }}</view>
									<view class="flex mb10" v-if="cv.discountMinPrice">
										<view class="vipLabel f-bt f11 l-h1">
											<view class="f-g-1 left wei">￥
												<text class="f13">{{cv.discountMinPrice}}</text>
												<text v-if="cv.isSpec">起</text>
											</view>
											<view class="f-g-0 right">会员价</view>
										</view>
									</view>
									<view class="labels" v-if="cv.discounts && cv.discounts.length">
										<view class="label goodlb" :style="{color:'#FF3131',borderColor:'#FF3131'}" v-for="(lv,li) in cv.discounts" :key="li">{{lv.discountLabel}}</view>
									</view>
									<view class="price mt20" v-if="cv.isShow!=1">
										<view v-if="cv.price" class="f-g-1 t-o-e f-y-e">
											￥{{ cv.price}}
											<text v-if="cv.isSpec"
												class="f12 c9 nowei ml5">起</text>
										</view>
										<view
											v-if="cv.goodsInventory!=0"
											class="f-g-0">
											<actions v-if="cv.price"
												:materials-btn="cv.isSpec"
												@materials="handdl(cv)" :number="gcnum(cv.id)" @add="handcar"
												@minus="handcar" :product="cv" />
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="car w100" v-if="carList">
			<view class="ac f-c p1 f12" v-if="!carOpen && carList.discountMoney>0">已享受折扣优惠，共减免{{carList.discountMoney}}元</view>
			<view class="f-bt carb">
				<view class="dfa f-g-1 left">
					<view v-if="carList.goodsList && !carList.goodsList.length" class="c9 f14 wei ml30">
						未选择商品
					</view>
					<view v-else  @click="showCar=true">
						<!-- <view style="position:relative" @click="showCar=true" class="gwcic f-c" :style="{background:subColor}">
							<text class="iconfont icon-gouwuchekong p5 bs6 c0" style="font-size:34rpx"></text>
							<u-badge bgColor="#f56c6c" max="99" :value="sum" :absolute="true" :offset="[-13,-13]"></u-badge>
						</view> -->
						<view class="ml20">
							<view class="cf">
								<text class="f18 cf wei6">￥{{carList.money}}</text>
							</view>
							<view class="f11 c9">已点{{carList.goodsCount}}个商品</view>
						</view>
					</view>
				</view>	
				<view class="btn f-g-0 f-c">
					<view class="c9 wei" style="color: #D9AC00;" v-if="carList.goodsList && !carList.goodsList.length">去购物车</view>
					<view class="c0 wei wh f-c" v-else @click="complete">去购物车</view>
				</view>
			</view>
		</view>
		<u-popup :show="showCar" :round="10" @close="showCar=false,carOpen = false" :safeAreaInsetBottom="false" @open="showCar=true,carOpen = true">
			<view class="p15 pb80 c0 f16">
				<view class="dfbc mb10">
					<text class="f14 wei">已选商品</text>
					<text class="f12 c9" @click="del">清空</text>
				</view>
				<view class="yxsp">
					<view class="dfbc bb1 p-10-0" v-for="(item,index) in carList.goodsList" :key="index">
						<view class="">
							<view class="f14">{{item.goods && item.goods.name}}</view>
							<view class="flex f-w f12">
								<view class="materials c9" v-if="item.attrData && item.attrData.spec">[{{ item.attrData.spec }}]</view>
								<view class="materials c9" v-if="item.attrData && item.attrData.attr">[{{ item.attrData.attr }}]</view>
								<view class="materials c9" v-if="item.attrData && item.attrData.matal">{{ item.attrData.matal }}</view>
								<view class="materials c9 mt5" v-if="item.setMealData && item.setMealData.length">
									<view v-for="(cv,ci) in item.setMealData" :key="ci">{{cv.name}}*{{cv.num}}
										<text v-if="cv.attrData && cv.attrData.attr" class="ml10">[{{ cv.attrData.attr }}]</text>
										<text v-if="cv.attrData && cv.attrData.matal" class="ml10">[{{ cv.attrData.matal }}]</text>
									</view>
								</view>
							</view>
						</view>
						<view class="dfa">
							<text class="mr15 f14">{{item.money}}</text>
							<view class="flex f-y-c">
								<view class="jh f-c jhb" @tap.stop="handcar({g: item,addwz: -1,})">
									<text class='iconfont icon-jianhao f26 nowei c0'></text>
								</view>
								<view class="number f16">{{item.num}}</view>
								<view class="jh f-c" :style="{background:subColor}"  @tap.stop="handcar({g: item,addwz: 1,})">
									<text class='iconfont icon-jiahao1 f26 nowei'></text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<product-modal ref="productModal" :product="product" :visible="productModalVisible"
			@cancel="closeProductDetailModal" @add-to-cart="handcar" @pay="pay" :carList="carList"
			:storeId="form.storeId"></product-modal>
		<u-modal :show="showDel" title="确定清空购物车吗？" :showCancelButton="true" :confirmColor="subColor" cancelText="取消"
			@cancel="showDel=false" @close="showDel=false" @confirm="delCar" ref="uModal"></u-modal>
		<u-popup :show="peoShow" :closeOnClickOverlay="true" round="10" @close="peoShow=false" @open="peoShow=true"
			z-index="10100">
			<view class='p-15-10 c0 f16' style="padding-bottom: 215px;">
				<view class="pb10">就餐人数<text class="f12 ml5">({{form.type && form.type.name}}{{form.name}})</text></view>
				<u-input v-model="value" placeholder="请输入就餐人数" border="none" shape="circle"
					:customStyle="{padding:'20rpx'}" disabled></u-input>
				<cuKeyboard ref="cukeyboard" @change="change"
					@confirm="confirm" @hide="peoShow=false">
				</cuKeyboard>
			</view>
		</u-popup>
		<view class="acshet">
			<u-action-sheet :actions="form.orderSn ? moreLists : moreList" @select="selectClick" :closeOnClickOverlay="true" :closeOnClickAction="false" @close="moreShow = false" :show="moreShow" cancelText='取消'></u-action-sheet>
		</view>
		<turntable ref="turntableRef" @save="checkOut" :v="form" ></turntable>
		<dLoading :status="loading"></dLoading>
	</view>
</template>

<script>
	import leeLinkage from './components/linkage.vue'
	import ProductModal from './components/product-modal.vue'
	import cuKeyboard from '@/components/cu-keyboard/cu-keyboard.vue'
	import Actions from "./components/actions.vue"
	import turntable from "../components/turntable.vue"
	import {
		mapState,
	} from 'vuex'
	export default {
		components: {
			leeLinkage,
			ProductModal,
			cuKeyboard,
			Actions,
			turntable,
		},
		async onLoad(options) {
			if (options && options.id) {
				this.id = options.id
				await this.getTableInfo()
				this.init()
			} else if (options && options.diningType) {
				this.form.diningType = options.diningType
				this.form.storeId = this.storeId
				this.form.id = 0
				this.title = '快速点单'
				this.init()
			}
		},
		onShow() {
			if(this.form && this.form.diningType){
				this.getCar()
			}
		},
		data() {
			return {
				subColor: uni.getStorageSync('subject_color'),
				showDel: false,
				showCar: false,
				show: false,
				searchValue:'',
				state: 0,
				value: '',
				num: 0,
				typeId: 1,
				queryForm: {
					// pageNo: 1,
					// pageSize: 10,
				},
				list: [],
				classfiy: [],
				form: {},
				categories: [],
				carList: {},
				goodInfo: {},
				product: {},
				productModalVisible: false,
				sum: 0,
				peoShow: false,
				scrollTop: 0,
				sIndex: 0,
				pstop: 0,
				ccId: 0,
				rectInfoList: [],
				moreShow:false,
				moreList: [
					{
						name:'转台',
						value:'zt'
					},
					{
						name:'撤台',
						value:'ct'
					}
				],
				moreLists: [
					{
						name:'转台',
						value:'zt'
					},
					{
						name:'并台',
						value:'bt'
					},
					{
						name:'撤台',
						value:'ct'
					}
				],
				title:'',
				loading:'',
				goodSetData:{},
				carOpen:false,
			}
		},
		computed: {
			...mapState({
				storeId: state => state.storeId,
			}),
			gcnum() {
				return id => this.carList && this.carList.goodsList && this.carList.goodsList.reduce((acc, cur) => {
					if (cur.spuId === id) {
						return acc += cur.num
					}
					return acc
				}, 0)
			},
		},
		methods: {
			async init() {
				this.loading = true
				await this.goodSet()
				this.fetchData()
				this.getCar()
			},
			async goodSet() {
				let {
					data
				} = await this.beg.request({
					url: this.api.config,
					data: {
						ident: 'sjdSetting'
					}
				})
				this.goodSetData = data ? data : {}
			},
			async getTableInfo() {
				let {
					data
				} = await this.beg.request({
					url: `${this.api.inTabel}/${this.id}`,
				})
				this.form = data ? data : {},
				this.title = `${data.area && data.area.name}-${data.type && data.type.name}-${data.name}`
			},
			async fetchData() {
				// this.dataList = []
				this.queryForm.diningType = this.form.diningType
				let {
					data
				} = await this.beg.request({
					url: this.api.storeGoods,
					data: this.queryForm,
				})
				this.categories = data
				this.ccId = this.categories.length && this.categories[0].id
				this.$nextTick(() => this.calcSize())
				this.loading = false
			},
			async getCar() {
				let {
					data
				} = await this.beg.request({
					url: this.api.cart,
					data: {
						diningType: this.form.diningType,
						storeId: this.form.storeId,
						tableId: this.form.id,
					}
				})
				this.carList = data ? data : {}
			},
			async handdl(product) {
				if(product && product.type==2){
					uni.navigateTo({
						url: `/pages/order/orderMeal/detail?goodId=${product.id}&storeId=${this.form.storeId}&diningType=${this.form.diningType}&tableId=${this.form.id}&dType=ins`
					})
				}else{
					let res = await this.beg.request({
						url: `${this.api.storeGoods}/${product.id}`,
						data: {
							storeId: this.form.storeId,
							diningType: this.form.diningType,
						}
					})
					this.product = res.data
					this.productModalVisible = true
					this.$refs['productModal'].open(product, this.form.storeId)
				}
			},
			toSearch() {
				uni.navigateTo({
					url: '/pages/home/search/index'
				})
			},
			handMenu(id, i) {
				this.sIndex = i
				this.pstop = this.categories.find(item => item.id == id).top
				this.$nextTick(() => this.ccId = id)
			},
			psroll({
				detail
			}) {
				const {
					scrollTop
				} = detail
				let tabs = this.categories.filter(item => item.top <= scrollTop).reverse()
				if (tabs.length > 0) {
					this.ccId = tabs[0].id
				}
				this.rectInfoList.forEach((item, index) => {
					if (scrollTop >= item.top && scrollTop <= item.bottom) {
						this.scrollTop = index * uni.upx2px(100);
						this.sIndex = index
					}
				})
			},
			calcSize() {
				let h = 0
				this.categories.forEach((item, i) => {
					let view = uni.createSelectorQuery().select(`#g-${item.id}`)
					view.fields({
						size: true,
						rect: true
					}, data => {
						item.top = h
						h += Math.floor(data.height)
						item.bottom = h
						this.rectInfoList[i] = {
							'top': item.top,
							'bottom': item.bottom
						}
					}).exec()
				})
			},
			async handcar(p) {
				try {
					let {data} =  await this.beg.request({
						url: this.api.cart,
						method: 'POST',
						data: {
							spuId: p.g.id,
							specMd5: p.g.specSwitch ? p.g.specInfo && p.g.specInfo.specMd5 : p.g.specMd5 || p.g
								.singleSpec.specMd5,
							attrData: p.g.specMd5 ? p.g.attrData || {} : (p.g.specSwitch || p.g.attrSwitch || p.g
								.materialSwitch) ? {
								spec: p.g.specSwitch && p.g.ggdata ? p.g.ggdata : '',
								attr: p.g.attribute,
								matal: p.g.jldata,
								material: p.g.material,
							} : {},
							num: p.addwz,
							storeId: this.form.storeId,
							tableId: this.form.id,
							diningType: this.form.diningType,
						}
					})
					if(data && data.cart) this.carList = data.cart
				} catch (e) {
					console.log(e)
				}
			},
			del() {
				if (this.carList.goodsList.length == 0) {
					uni.showToast({
						title: '购物车无数据！',
						icon: 'none',
						duration: 800
					});
				} else {
					this.showCar = false
					this.showDel = true
					this.carOpen = false
				}
				// this.list = []
			},
			//去确认下单
			complete() {
				this.showCar = false
				this.carOpen = false
				if (this.form.diningType == 6) {
					uni.navigateTo({
						url: `/pages/order/orders/detail`
					})
				} else {
					uni.navigateTo({
						url: `/pages/order/orders/detail?id=${this.id}`
					})
				}
			},
			async delCar() {
				let {
					msg
				} = await this.beg.request({
					url: this.api.clearCart,
					method: 'DELETE',
					data: {
						tableId: this.form.id,
						storeId: this.form.storeId,
						diningType: this.form.diningType,
					}
				})
				uni.showToast({
					title: msg,
					icon: 'none'
				});
				this.showCar = false
				this.getCar()
				this.showDel = false
			},
			async clickPeo() {
				this.value = this.form.people
				this.peoShow = true
				this.$nextTick(() => this.$refs.cukeyboard.open())
			},
			change(e) {
				this.value = e;
			},
			closeProductDetailModal(){},
			pay(){},
			checkOut(){},
			async confirm(e) {
				if (+this.value) {
					await this.beg.request({
						url: `${this.api.inTabel}/${this.form.id}`,
						method: 'PUT',
						data: {
							people: +this.value
						}
					})
					this.peoShow = false
					this.getTableInfo()
				} else {
					this.peoShow = false
					uni.$u.toast('请输入就餐人数！');
				}
			},
			 selectClick(e){
				 this.moreShow = false
				if(e.value=='ct'){
					uni.showModal({
						title: '提示',
						content: '请确认是否撤销此桌台吗?',
						success: async (res) => {
							if (res.confirm) {
								let { msg , code } = await this.beg.request({
									url: `${this.api.backTb}/${this.form.id}`,
									method: 'POST'
								})
								uni.showToast({
									title: msg,
									icon: 'none',
									duration: 2000
								})
								if(code && code==200){
									this.moreShow = false
									setTimeout(() =>{
										// #ifdef MP-WEIXIN
											uni.reLaunch({
												url: `/pages/order/orders/index`
											})
										// #endif
										// #ifndef MP-WEIXIN
											uni.switchTab ({
												url: `/pages/index/index`
											})
										// #endif
									},800)
								}
							} else if (res.cancel) {
								this.moreShow = false
							}
						}
					});
				}else if(e.value=='zt'){
					this.$refs['turntableRef'].open('turntable')
				}else if(e.value=='bt'){
					this.$refs['turntableRef'].open('parallel')
				}
			},
		}
	}
</script>

<style lang="scss" scoped>

	/deep/.u-popup {
		flex: 0 !important;
	}

	.car {
		position: fixed;
		bottom: 60rpx;
		left: 0;
		z-index: 10086;
		width: 90%;
		margin: 0 40rpx;
		overflow: hidden;
		.carb{
			border-radius: 60rpx;
			overflow: hidden;
		}
		.left{
			background: #393534;
			height: 90rpx;
		}
		.btn{
			width: 30%;
			background:linear-gradient(to right, #FDDA34, #fdc450);
		}
	}

	.main {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.gleft {
		width: 170rpx;
		flex: 0 0 170rpx;
		background-color: #F9F9FB;
	}

	.leftwrp {
		height: auto;

		.mi {
			position: relative;
			height: 80rpx;
			color: #999;
			font-size: 26rpx;
			background: #fff;

			&:nth-last-child(1) {
				margin-bottom: 100rpx;
			}

			.sitem {
				height: 100%;
				margin: auto;
				background: #F9F9FB;
				overflow: hidden;

				.title {
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				&.ysyj {
					border-top-right-radius: 14rpx;
				}

				&.yxyj {
					border-bottom-right-radius: 14rpx;
				}

				&.active {
					background-color: #ffffff;
					color: #000;
					font-weight: bold;
					// border-left: 7rpx solid #4cd964;
				}

			}
		}
	}

	.gright {
		flex: 1;

		.wrp {
			padding: 0 20rpx;
			padding-bottom: 280rpx;
		}

		.ads1,
		.ads2 {
			height: 300rpx;
		}

		.ads1 {
			margin-bottom: 20rpx;
		}
		
		.labels {
			display: flex;
			font-size: 20rpx;
			margin-bottom: 6rpx;
			overflow: hidden;
			// height: 46rpx;
			flex-wrap: wrap;
			.label {
				max-width: 50%;
				padding: 4rpx 10rpx;
				margin-right: 10rpx;
				// margin-bottom: 10rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				border-radius: 4rpx;
			}
			.goodlb{
				font-size: 20rpx;
				padding: 2rpx 6rpx;
				border: 2rpx solid #BABABA;
				color: #BABABA;
				margin-bottom: 10rpx;
			}
		}

	}

	.glist {
		.gname {
			padding-bottom: 20rpx;
			font-weight: bold;
			font-size: 26rpx;
			color: #000;
			.cn{
				padding: 10rpx;
				font-weight: normal;
				color: #000;
				border-radius: 10rpx;
			}
			.cleal{
				width: 8rpx;
				height: 8rpx;
				border-radius: 50%;
				background: #999;
			}
		}

		.gwrp {
			display: flex;
			flex-direction: column;
			margin-bottom: 20rpx;
			margin-top: 20rpx;
		}

		.goods {
			// &:nth-last-child(1) {
			// 	border-bottom: none;
			// }
			
			display: flex;
			margin-bottom: 36rpx;
			padding-bottom: 36rpx;
			border-bottom: 2rpx solid #f0f0f0;

			.image {
				width: 120rpx;
				height: 120rpx;
				flex-shrink: 0;
				position: relative;
			}

			.ysq {
				height: 42rpx;
				background: rgba(0, 0, 0, 0.5)
			}

			.content {
				flex: 1;
				display: flex;
				flex-direction: column;
				overflow: hidden;

				.name {
					font-size: 28rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
					margin-bottom: 8rpx;
				}

				.price {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
			}
		}
	}

	.input {
		padding: 0 10px;
	}

	.gwcic{
		background: #f5f5f5;
		border-radius: 50%;
		width: 90rpx;
		height: 90rpx;
	}
	
	.acshet{
		z-index: 10111;
	}
	
	.f40{
		font-size: 40rpx;
	}
	
	.f42{
		font-size: 42rpx;
	}
	
	.number{
		text-align: center;
		width: 80rpx;
	}
	
	.yxsp{
		max-height: 800rpx;
		overflow-y: scroll;
	}
	
	.ac{
		height: 34px;
		background: #FFF7E2;
		border-radius: 20rpx;
	}
</style>